#include <iostream>
#include <string>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// ./client server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:./client server_ip server_port" << std::endl;
        return 1;
    }

    // 获取ip和端口，建立对应的socket
    std::string server_ip = argv[1];
    int server_prot = std::stoi(argv[2]); 
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket failed " << std::endl;
        return 2;
    }

    // 填充要连接的服务器的信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_prot);                  // 主机字节序转换为网络字节序
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str()); // 点分十进制转换为网络的二进制

    // client仍然不需要显式的进行bind
    // client也不能进行直接read或者write，需要先建立连接服务器(connect)
    // connect底层会进行bind，
    int n = ::connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)); //TODO..
    if(n < 0)
    {
        std::cout << "connect failed" << std::endl;
        return 3;
    }

    ::close(sockfd);
    return 0;
}